package com.papers.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.domain.dto.RoleDTO;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.exception.ServiceException;
import com.papers.common.helper.LoginHelper;
import com.papers.common.utils.DateUtils;
import com.papers.common.utils.StringUtils;
import com.papers.juan.domain.TJuanQuestion;
import com.papers.juan.mapper.TJuanQuestionMapper;
import com.papers.system.domain.TJuanChapter;
import com.papers.system.domain.TJuanKnowledge;
import com.papers.system.domain.bo.TJuanChapterBo;
import com.papers.system.domain.dto.TJuanChapterDto;
import com.papers.system.domain.dto.TJuanChapterSortDto;
import com.papers.system.domain.vo.TJuanChapterOutVo;
import com.papers.system.domain.vo.TJuanChapterPutVo;
import com.papers.system.domain.vo.TJuanChapterVo;
import com.papers.system.domain.vo.TJuanCourseTreeVo;
import com.papers.system.domain.vo.TJuanLeftTreeListVo;
import com.papers.system.domain.vo.TJuanLeftTreeVo;
import com.papers.system.domain.vo.TJuanMajorTreeVo;
import com.papers.system.mapper.TJuanChapterMapper;
import com.papers.system.mapper.TJuanCourseMapper;
import com.papers.system.mapper.TJuanDepartmentMapper;
import com.papers.system.mapper.TJuanKnowledgeMapper;
import com.papers.system.mapper.TJuanMajorMapper;
import com.papers.system.service.ITJuanChapterService;
import com.papers.system.service.ITJuanKnowledgeService;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 章节Service业务层处理
 *
 * @author papers
 * @date 2022-10-08
 */
@RequiredArgsConstructor
@Service
public class TJuanChapterServiceImpl implements ITJuanChapterService {

    private final TJuanChapterMapper tJuanChapterMapper;

    private final TJuanCourseMapper tJuanCourseMapper;

    private final TJuanDepartmentMapper departmentMapper;

    private final TJuanMajorMapper majorMapper;

    private final TJuanKnowledgeMapper juanKnowledgeMapper;

    private final TJuanQuestionMapper juanQuestionMapper;

    private final ITJuanKnowledgeService itJuanKnowledgeServicege;

    /**
     * 查询章节
     */
    @Override
    public TJuanChapterVo queryById(String chapterId) {
        TJuanChapterVo tJuanChapterVo = tJuanChapterMapper.getVoById(chapterId);
        return tJuanChapterVo;
    }

    /**
     * 查询章节列表
     */
    @Override
    public TableDataInfo<TJuanChapterVo> queryPageList(TJuanChapterDto dto, PageQuery pageQuery) {
        // LambdaQueryWrapper<TJuanChapter> lqw = buildQueryWrapper(bo);
        // Page<TJuanChapterVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<TJuanChapterVo> page = tJuanChapterMapper.getChapterByPage(pageQuery.build(), dto);
        return TableDataInfo.build(page);
    }

    /**
     * 查询章节列表
     */
    @Override
    public List<TJuanChapterVo> queryList(TJuanChapterBo bo) {
        LambdaQueryWrapper<TJuanChapter> lqw = buildQueryWrapper(bo);
        return tJuanChapterMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TJuanChapter> buildQueryWrapper(TJuanChapterBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TJuanChapter> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCourseId()), TJuanChapter::getCourseId, bo.getCourseId());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterCode()), TJuanChapter::getChapterCode, bo.getChapterCode());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterParentId()), TJuanChapter::getChapterParentId, bo.getChapterParentId());
        lqw.like(StringUtils.isNotBlank(bo.getChapterName()), TJuanChapter::getChapterName, bo.getChapterName());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterType()), TJuanChapter::getChapterType, bo.getChapterType());
        lqw.eq(StringUtils.isNotBlank(bo.getChapterDes()), TJuanChapter::getChapterDes, bo.getChapterDes());
        lqw.eq(StringUtils.isNotBlank(bo.getCreatedBy()), TJuanChapter::getCreatedBy, bo.getCreatedBy());
        lqw.eq(bo.getCreatedTime() != null, TJuanChapter::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getUpdatedBy()), TJuanChapter::getUpdatedBy, bo.getUpdatedBy());
        lqw.eq(bo.getUpdatedTime() != null, TJuanChapter::getUpdatedTime, bo.getUpdatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getParentId()), TJuanChapter::getParentId, bo.getParentId());
        return lqw;
    }

    /**
     * 新增章节
     */
    @Override
    public Boolean insertByBo(TJuanChapterBo bo) {
        TJuanChapter add = BeanUtil.toBean(bo, TJuanChapter.class);
        add.setParentId("0");
        add.setUpdatedBy(LoginHelper.getUsername());
        add.setCreatedBy(LoginHelper.getUsername());
        add.setUpdatedTime(DateUtils.getNowDate());
        add.setCreatedTime(DateUtils.getNowDate());



        //正常+1
        LambdaQueryWrapper<TJuanChapter> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.orderByDesc(TJuanChapter::getChapterCode)
            .eq(TJuanChapter::getCourseId,bo.getCourseId())
            .last("LIMIT 1");
        TJuanChapter chapter = tJuanChapterMapper.selectOne(queryWrapper1);

        //查询本课程所有
        QueryWrapper<TJuanChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.lambda().eq(TJuanChapter::getCourseId,bo.getCourseId());
        chapterQueryWrapper.lambda().orderByAsc(TJuanChapter::getChapterCode);
        List<TJuanChapter> chapterList = tJuanChapterMapper.selectList(chapterQueryWrapper);

        if (chapterList.size()>99){
            throw new ServiceException("已达到章节最大数量，请联系管理员");
        }

        List<Integer> badNum = new ArrayList<>();
        for (int i=1;i<=chapterList.size();i++){
            TJuanChapter chapter1 = chapterList.get(i-1);
            if (Integer.parseInt(chapter1.getChapterCode().substring(0,2))!=i){
                badNum.add(i);
            }
        }
        if (ObjectUtils.isEmpty(chapter)){
            add.setChapterCode("01");
            add.setChapterSort(1);
        }else if (badNum.size()!=0){
            if (badNum.get(0)<10){
                String a = "0"+badNum.get(0);
                add.setChapterCode(a);
            }else {
                add.setChapterCode(String.valueOf(badNum.get(0)));
            }
        }else {
            if (Integer.parseInt(chapter.getChapterCode())<9){
                add.setChapterCode("0"+(Integer.parseInt(chapter.getChapterCode())+1));
            }else {
                add.setChapterCode(String.valueOf(Integer.parseInt(chapter.getChapterCode())+1));
            }
        }

        //如果未添加数据，设置00


        /*拼接parentId*/
        if (bo.getChapterParentId().equals("0")) {
            add.setParentId("0");
        } else {
            QueryWrapper<TJuanChapter> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TJuanChapter::getChapterId, bo.getChapterParentId());
            // 获取到父节点的parentids
            TJuanChapterVo tJuanChapterVo = tJuanChapterMapper.selectVoOne(queryWrapper);

            String parentId = tJuanChapterVo.getParentId();
            parentId += "," + tJuanChapterVo.getChapterId();    // 拼接父节点（vo）的章节id
            add.setParentId(parentId);
        }


        validEntityBeforeSave(add);

        if (bo.getChapterSort()==null){
            //查询本课程所有
            QueryWrapper<TJuanChapter> cqw = new QueryWrapper<>();
            cqw.lambda().eq(TJuanChapter::getCourseId,bo.getCourseId());
            cqw.lambda().orderByAsc(TJuanChapter::getChapterSort);
            List<TJuanChapter> chapters = tJuanChapterMapper.selectList(cqw);
            if (ObjectUtils.isEmpty(chapters)){
                add.setChapterSort(1);
            }else {
                add.setChapterSort(chapters.size()+1);
            }

        }else {
            QueryWrapper<TJuanChapter> cqw = new QueryWrapper<>();
            cqw.lambda().eq(TJuanChapter::getCourseId,bo.getCourseId());
            cqw.lambda().orderByAsc(TJuanChapter::getChapterSort);
            cqw.lambda().ge(TJuanChapter::getChapterSort,bo.getChapterSort());
            List<TJuanChapter> list = tJuanChapterMapper.selectList(cqw);

            list.forEach(item ->{
                Integer sort = item.getChapterSort()+1;
                item.setChapterSort(sort);
            });
            tJuanChapterMapper.insertOrUpdateBatch(list);
            //插入的
            add.setChapterSort(bo.getChapterSort());
        }

        boolean flag = tJuanChapterMapper.insert(add) > 0;
        if (flag) {
            bo.setChapterId(add.getChapterId());
        }

        return flag;
    }


    /**
     * 修改章节
     */
    @Override
    public Boolean updateByBo(TJuanChapterBo bo) {
        TJuanChapter update = BeanUtil.toBean(bo, TJuanChapter.class);
        update.setUpdatedBy(LoginHelper.getUsername());
        update.setUpdatedTime(DateUtils.getNowDate());

        /*拼接parentId*/
        if (bo.getChapterParentId().equals("0")) {
            update.setParentId("0");
        } else {
            QueryWrapper<TJuanChapter> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TJuanChapter::getChapterId, bo.getChapterParentId());
            // 获取到父节点的parentids
            TJuanChapterVo tJuanChapterVo = tJuanChapterMapper.selectVoOne(queryWrapper);

            String parentId = tJuanChapterVo.getParentId();
            parentId += "," + tJuanChapterVo.getChapterId();    // 拼接父节点（vo）的章节id
            update.setParentId(parentId);
        }

        validEntityBeforeSave(update);
        return tJuanChapterMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TJuanChapter entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 查询章节
     *
     * @param chapterId
     * @return
     */
    @Override
    public TJuanChapter getOne(String chapterId) {
        LambdaQueryWrapper<TJuanChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != chapterId, TJuanChapter::getChapterName, chapterId)
            .last("limit 1");
        TJuanChapter tJuanChapter = tJuanChapterMapper.selectOne(queryWrapper);
        return tJuanChapter;
    }

    /**
     * 查询章节树
     *
     * @param courseId
     * @return
     */
    @Override
    public List<TJuanLeftTreeVo> getChapterTreeList(String courseId) {
        //查看本人的角色
        List<RoleDTO> roles = LoginHelper.getRoles();
        //如果角色有且只有一个教员，则他只能看到他自己创建的题库
        String userName = null;
        if (roles.size() == 1) {
            if ("教员".equals(roles.get(0).getRoleName())) {
                userName = LoginHelper.getUsername();
            }
        }
        List<TJuanLeftTreeVo> courses = tJuanCourseMapper.getLeftTree(courseId, userName);
        // 根据 courseId 查询所有的章节列表
        List<TJuanLeftTreeVo> chapterList = tJuanChapterMapper.getChapterTree();
        Map<String, List<TJuanLeftTreeVo>> collect = chapterList.stream().collect(Collectors.groupingBy(TJuanLeftTreeVo::getParentId));
        for (TJuanLeftTreeVo item : courses){
            if (collect.get(item.getId())!= null){
                item.setChildren(collect.get(item.getId()));
            }
        }
        return courses;
//        List<TJuanLeftTreeVo> list = getChildrenList(chapterList, "0");
//        List<TJuanLeftTreeVo> list = courseMapper.getCourseTreeList(courseId);
//        List<TJuanLeftTreeVo> courseList = tJuanChapterMapper.selectChapterList();
//        Map<String, List<TJuanLeftTreeVo>> collect = courseList.stream().collect(Collectors.groupingBy(TJuanLeftTreeVo::getDepartment));
//        for (TJuanLeftTreeVo item :list) {
//            List<TJuanLeftTreeVo> vo = collect.get(item.getId());
//            if(null != vo){
//                item.setChildren(vo);
//            }
//        }
    }
    /**
     * 导出excel
     *
     * @param
     * @return
     */
    @Override
    public List<TJuanChapterPutVo> OutputList(TJuanChapterBo bo) {
        return tJuanChapterMapper.OutputChapter(bo);
    }


    /**
     * 批量导入
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveBatch(List<TJuanChapterOutVo> list,String courseId) {
        List<TJuanChapterOutVo> list1 = new ArrayList<>();
        List<TJuanChapterOutVo> list2 = new ArrayList<>();
        for (TJuanChapterOutVo item:list){
            if (null != item.getChapterCode()){
                list1.add(item);
            }
            else {
                list2.add(item);
            }
        }
        list1.addAll(list2);

        String newCode;
        int newSort;
        for (TJuanChapterOutVo item:list1){
            if (item.getChapterName()==null){
                return R.fail("存在章节名称为空，无法导入");
            }
            if(null!=item.getChapterCode() && item.getChapterCode().length()==1){
                item.setChapterCode("0"+ item.getChapterCode());
            }
            item.setCourseId(courseId);

            //没有code
            if (ObjectUtils.isNull(item.getChapterCode())){
                LambdaQueryWrapper<TJuanChapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
                chapterLambdaQueryWrapper.eq(TJuanChapter::getCourseId,courseId);
                chapterLambdaQueryWrapper.orderByDesc(TJuanChapter::getChapterCode)
                    .last("LIMIT 1");
                TJuanChapter chapter = tJuanChapterMapper.selectOne(chapterLambdaQueryWrapper);
                if (ObjectUtils.isNull(chapter)){
                    newCode = "01";
                    item.setChapterSort(1);
                }
                else {
                    LambdaQueryWrapper<TJuanChapter> cqw = new LambdaQueryWrapper<>();
                    cqw.eq(TJuanChapter::getCourseId,courseId);
                    cqw.orderByDesc(TJuanChapter::getChapterSort)
                        .last("LIMIT 1");
                    TJuanChapter lastchapter = tJuanChapterMapper.selectOne(cqw);
                    item.setChapterSort(lastchapter.getChapterSort()+1);

                    List<String> chapters = tJuanChapterMapper.selectCodeList(courseId);
                    int oldCode = Integer.parseInt(chapter.getChapterCode());
                    if (oldCode != chapters.size()) {
                        int currentCode = 01;
                        for (String code : chapters) {
                            if (currentCode != Integer.parseInt(code)) {
                                oldCode = currentCode - 1;
                                break;
                            }
                            currentCode ++;
                        }
                    }
                    oldCode++;
                    if (oldCode > 99) {
                        return R.fail("已达到章节最大数量，请联系管理员");
                    }
                    newCode = String.format("%02d", oldCode);
                }
                //添加sort
                LambdaQueryWrapper<TJuanChapter> clqw= new LambdaQueryWrapper<>();
                clqw.eq(TJuanChapter::getCourseId,courseId);
                List<TJuanChapter> chapterList = tJuanChapterMapper.selectList(clqw);
                item.setChapterSort(chapterList.size()+1);
                item.setChapterCode(newCode);
                item.setChapterParentId("0");
                item.setCreatedBy(LoginHelper.getUsername());
                item.setCreatedTime(DateUtils.getNowDate());
            }
            //有code
            else {
                if (item.getChapterCode().length() != 2 || Integer.parseInt(item.getChapterCode()) <= 0 || Integer.parseInt(item.getChapterCode()) > 99) {
                    return R.fail("存在章节编号格式有误，请修改");
                }
                //重复，更新信息
                if (codeVerify(item.getChapterCode(),courseId)) {
                    LambdaQueryWrapper<TJuanChapter> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TJuanChapter::getCourseId,courseId);
                    queryWrapper.eq(TJuanChapter::getChapterCode, item.getChapterCode());
                    TJuanChapter chapter = tJuanChapterMapper.selectOne(queryWrapper);
                    item.setChapterId(chapter.getChapterId());
                    item.setChapterParentId(chapter.getChapterParentId());
                }
                //没有重复，新增
                else {
                    item.setCreatedBy(LoginHelper.getUsername());
                    item.setCreatedTime(DateUtils.getNowDate());
                    item.setChapterParentId("0");
                    //添加sort
                    LambdaQueryWrapper<TJuanChapter> chapterLambdaQueryWrapper= new LambdaQueryWrapper<>();
                    chapterLambdaQueryWrapper.eq(TJuanChapter::getCourseId,courseId);
                    List<TJuanChapter> chapterList = tJuanChapterMapper.selectList(chapterLambdaQueryWrapper);
                    item.setChapterSort(chapterList.size()+1);
                }
            }
            item.setCourseId(courseId);
            item.setUpdatedBy(LoginHelper.getUsername());
            item.setUpdatedTime(DateUtils.getNowDate());
            TJuanChapter tJuanChapter = BeanUtil.copyProperties(item, TJuanChapter.class);
            tJuanChapterMapper.insertOrUpdate(tJuanChapter);

        }
        return R.ok("导入成功");
//        List<TJuanChapter> chapterList = new ArrayList<>();
//
//        list.stream().forEach(item -> {
//
//            TJuanChapter chapter = new TJuanChapter();
//            LambdaQueryWrapper<TJuanCourse> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            courseLambdaQueryWrapper.eq(TJuanCourse::getCourseCode,item.getCourseCode());
//            TJuanCourse tJuanCourse = tJuanCourseMapper.selectOne(courseLambdaQueryWrapper);
//            //如果课程code无效，return
//            if (tJuanCourse==null){
//                return;
//            }
//            //code有效，进行更新或添加操作
//            LambdaQueryWrapper<TJuanChapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            chapterLambdaQueryWrapper.eq(TJuanChapter::getChapterCode,item.getChapterCode());
//            TJuanChapter one = tJuanChapterMapper.selectOne(chapterLambdaQueryWrapper);
//
//            if (one!=null){
//                //更新
//                chapter.setChapterId(one.getChapterId());
//                chapter.setChapterCode(one.getChapterCode());
//                chapter.setCourseId(tJuanCourse.getCourseId());
//                chapter.setChapterName(item.getChapterName());
//                chapter.setChapterType(item.getChapterType());
//                chapter.setChapterDes(item.getChapterDes());
//                //更新信息
//                chapter.setUpdatedBy(LoginHelper.getUsername());
//                chapter.setUpdatedTime(DateUtils.getNowDate());
//            }else {
//                //新增
//                chapter.setChapterCode(item.getChapterCode());
//                chapter.setCourseId(tJuanCourse.getCourseId());
//                chapter.setChapterName(item.getChapterName());
//                chapter.setChapterType(item.getChapterType());
//                chapter.setChapterDes(item.getChapterDes());
//                chapter.setChapterParentId("0");
//                chapter.setParentId("0");
//                //创建信息
//                chapter.setCreatedBy(LoginHelper.getUsername());
//                chapter.setCreatedTime(DateUtils.getNowDate());
//                chapter.setUpdatedBy(LoginHelper.getUsername());
//                chapter.setUpdatedTime(DateUtils.getNowDate());
//            }
//
//            chapterList.add(chapter);
//
//        });
//        return tJuanChapterMapper.insertOrUpdateBatch(chapterList);
    }

    private boolean codeVerify(String code,String courseId) {
        LambdaQueryWrapper<TJuanChapter> chapterLqw = new LambdaQueryWrapper<>();
        chapterLqw.eq(TJuanChapter::getCourseId,courseId);
        chapterLqw.eq(TJuanChapter::getChapterCode,code);
        TJuanChapter one = tJuanChapterMapper.selectOne(chapterLqw);
        if (ObjectUtils.isEmpty(one)){
            return false;
        }
        return true;
    }

    @Override
    public List<TJuanChapterVo> getChapterList(TJuanChapterBo bo) {
        List<TJuanChapterVo> chapterList = tJuanChapterMapper.queryChapterList(bo);
        if(StringUtils.isNotBlank(bo.getCourseId())){
            return chapterList;
        }
        return new ArrayList<>();
    }

    /**
     * 查询课程树
     * @return
     */
    @Override
    public List<TJuanCourseTreeVo> getCourseTreeList() {
        //查 院系
        List<TJuanLeftTreeVo> departTreeList = departmentMapper.getDepartTreeList();
        List<String> collect = departTreeList.stream().map(item -> {
            item.setParentId("0");
            String id= item.getId();
            return id;
        }).collect(Collectors.toList());

        //查 专业
        if (ObjectUtils.isNull(collect)){
            return null;
        }
        List<TJuanMajorTreeVo> majorTreeList = majorMapper.getMajorTree(collect);
        List<String> collect1 = majorTreeList.stream().map(item -> {
            String id = item.getId();
            return id;
        }).collect(Collectors.toList());

        //查 课程
        if (ObjectUtils.isNull(collect1)){
            return null;
        }
        List<TJuanLeftTreeListVo> courseList = tJuanCourseMapper.getCourseMajorTreeVo(StringUtils.strip(collect1.toString(), "[]"));
        Map<String, List<TJuanLeftTreeListVo>> map = courseList.stream().collect(Collectors.groupingBy(TJuanLeftTreeListVo::getParentId));
        for (TJuanMajorTreeVo vo : majorTreeList) {
            vo.setChildren(map.get(vo.getId()));
        }

        List<TJuanCourseTreeVo> depart = departmentMapper.getDepartCourseTree();
        Map<String, List<TJuanMajorTreeVo>> map1 = majorTreeList.stream().collect(Collectors.groupingBy(TJuanMajorTreeVo::getParentId));
        for (TJuanCourseTreeVo vo : depart) {
            vo.setChildren(map1.get(vo.getId()));
        }
        return depart;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> deleteByIds(String[] chapterIds) {
        List<TJuanQuestion> questionDelete = new ArrayList<>();
        List<TJuanKnowledge> knowledgeDelete = new ArrayList<>();
        //查看章节是否存在子节点、知识点、题目
        for (String id : chapterIds) {
            LambdaQueryWrapper<TJuanChapter> children = new LambdaQueryWrapper<>();
            children.eq(TJuanChapter::getChapterParentId, id);
            List<TJuanChapter> childrenData = tJuanChapterMapper.selectList(children);
            if (CollectionUtils.isNotEmpty(childrenData)) {
                return R.fail("该章节存在子节点未删除");
            }
            LambdaQueryWrapper<TJuanKnowledge> knowledge = new LambdaQueryWrapper<>();
            knowledge.eq(TJuanKnowledge::getChapterId, id);
            List<TJuanKnowledge> knowledgeData = juanKnowledgeMapper.selectList(knowledge);
            if (CollectionUtils.isNotEmpty(knowledgeData)) {
//                return R.fail("该章节存在知识点未删除");
                //删除知识点
                knowledgeDelete.addAll(knowledgeData);
            }
            LambdaQueryWrapper<TJuanQuestion> question = new LambdaQueryWrapper<>();
            question.eq(TJuanQuestion::getChapterId, id);
            List<TJuanQuestion> questionData = juanQuestionMapper.selectList(question);
            if (CollectionUtils.isNotEmpty(questionData)) {
//                return R.fail("该章节存在题目未删除");
                //删除题目
                questionDelete.addAll(questionData);
            }
        }
        //删除
        if (CollectionUtils.isNotEmpty(questionDelete)) {
            juanQuestionMapper.deleteBatchIds(questionDelete);
        }
        if (CollectionUtils.isNotEmpty(knowledgeDelete)) {
            List<String> knowledges = new ArrayList<>();
            for (TJuanKnowledge tJuanKnowledge : knowledgeDelete) {
                knowledges.add(tJuanKnowledge.getKnowledgeId());
            }
            String[] ans2 = knowledges.toArray(new String[knowledges.size()]);
            itJuanKnowledgeServicege.deleteKnowledge(ans2);
        }
        LambdaQueryWrapper<TJuanChapter> chapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chapterLambdaQueryWrapper.eq(TJuanChapter::getChapterId,chapterIds[0]);
        TJuanChapter chapter = tJuanChapterMapper.selectOne(chapterLambdaQueryWrapper);

        QueryWrapper<TJuanChapter> cqw = new QueryWrapper<>();
        cqw.lambda().eq(TJuanChapter::getCourseId,chapter.getCourseId());
        cqw.lambda().orderByAsc(TJuanChapter::getChapterSort);
        cqw.lambda().ge(TJuanChapter::getChapterSort,chapter.getChapterSort());
        List<TJuanChapter> list = tJuanChapterMapper.selectList(cqw);

        list.forEach(item ->{
            Integer sort = item.getChapterSort()-1;
            item.setChapterSort(sort);
        });

        tJuanChapterMapper.insertOrUpdateBatch(list);

        int flag = tJuanChapterMapper.deleteBatchIds(Arrays.asList(chapterIds));
        if (flag > 0) {
            return R.ok("删除成功!");
        }
        return R.fail("删除失败!");
    }

    @Override
    public int ChapterCodeUnique(TJuanChapterBo bo) {
        LambdaQueryWrapper<TJuanChapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TJuanChapter::getChapterCode, bo.getChapterCode());
        queryWrapper.last("LIMIT 1");
        TJuanChapterVo tJuanChapterVo = tJuanChapterMapper.selectVoOne(queryWrapper);
        /*如存在相同code的对象，返回0*/
        if (tJuanChapterVo == null) {
            return 1;
        }
        if (tJuanChapterVo.getChapterId().equals(bo.getChapterId())) {
            return 1;
        }
        return 0;
    }

    @Override
    public R<Void> sort(TJuanChapterSortDto dto) {
        Integer current = dto.getCurrentSort();
        Integer target = dto.getTargetSort();

        String courseId = dto.getCourseId();
        //当前
        LambdaQueryWrapper<TJuanChapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TJuanChapter::getCourseId,courseId);
        lqw.eq(TJuanChapter::getChapterSort,current);
        TJuanChapter tJuanChapter = tJuanChapterMapper.selectOne(lqw);
        tJuanChapter.setChapterSort(target);
        // 获取当前和目标之间的数据
        QueryWrapper<TJuanChapter> queryWrapper = new QueryWrapper<>();
        if (target < current){
            queryWrapper.eq("COURSE_ID",dto.getCourseId())
                .between("CHAPTER_SORT",target,current);
        }else {
            queryWrapper.eq("COURSE_ID",dto.getCourseId())
                .between("CHAPTER_SORT",current,target);
        }
        List<TJuanChapter> list = tJuanChapterMapper.selectList(queryWrapper);
        list = list.stream().filter(item -> item.getChapterSort() != current).map(item -> {
            if (target < current) {
                item.setChapterSort(item.getChapterSort() + 1);
            } else {
                item.setChapterSort(item.getChapterSort() - 1);
            }
            return item;
        }).collect(Collectors.toList());
        list.add(tJuanChapter);
        list.stream().sorted(Comparator.comparing(TJuanChapter::getChapterSort));
        if (tJuanChapterMapper.insertOrUpdateBatch(list)) {
            return R.ok();
        }
        ;
        return R.fail();
    }


    /**
     * 递归获取章节list
     *
     * @param treeList
     * @param id
     * @return
     */
    private List<TJuanLeftTreeVo> getChildrenList(List<TJuanLeftTreeVo> treeList, String id) {
        List<TJuanLeftTreeVo> children = new ArrayList<>();
        for (TJuanLeftTreeVo leftTreeVo : treeList) {
            // 判断该节点的父id，是否与传入的父id相同，相同则递归设置其子节点，并将该节点放入children集合中
            if (StringUtil.equals(leftTreeVo.getParentId(), id)) {
                // 递归设置其子节点
                leftTreeVo.setChildren(getChildrenList(treeList, leftTreeVo.getId()));
                // 放入children集合
                children.add(leftTreeVo);
            }
        }
        return children;
    }



}
